<?php
/**
 * Created by PhpStorm.
 * User: yanwenqing
 * Date: 2018/8/10
 * Time: 12:03
 */
namespace Home\Service;

class YoCasService{

    protected $ticketService;

    public function __construct()
    {
        $this->ticketService = new ClientService();
    }

    /**
     * 退出操作
     */
    public function logout(){
        $this->localLogout();
        $cas_url = $this->ticketService->server.'/cas/logout';
        header('Location:'.$cas_url);
        die;
    }

    public function localLogout(){
        session_unset();
        session_destroy();
    }

    /**
     * @param bool $renew
     * @return bool
     * @throws \Exception
     */
    public function checkRedirectToCas($renew = false){
        // 检测一下用户是否已经登陆了
        if(!$this->checkLogin()){
            // 检测一下是否存在ticket参数
            if($this->ticketService->ticket){
                if($this->auth()){
                    $this->successHandle();
                }else{
                    $this->authFailed();
                }
            }else{
                $this->ticketService->setLoginUrl();
                if($this->ticketService->loginUrl){
                    header('Location:'.$this->ticketService->loginUrl);
                }
            }
        }

        // 登陆成功也可能存在ticket
        if($_GET['ticket']) throw new \Exception('已经登陆，传递了无效的ticket');

        return true;
    }

    /**
     * 认证
     * @throws \Exception
     */
    public function auth(){
        $validateResult = $this->ticketService->validateCas($validate_url, $text_response, $tree_response);

        return $validateResult;
    }

    /**
     * 认证失败
     * @throws \Exception
     */
    public function authFailed(){
        if (isset($_SESSION['phpCAS']['auth_checked'])) {
            unset($_SESSION['phpCAS']['auth_checked']);
        }
        throw new \Exception('auth failed');
    }

    /**
     * ticket验证成功后，执行的操作
     * 去除ticket参数，然后跳转到首页
     */
    public function successHandle(){
        $_SESSION['phpCAS']['user'] = $this->ticketService->user;
        session_write_close();
        header('Location: '.$this->ticketService->getUrl());
        flush();
    }

    /**
     * 检测用户是否已经登陆了
     * @return mixed
     */
    public function checkLogin(){
        return $_SESSION['phpCAS']['user'];
    }
}